/**
 * Created by lumix on 2015/4/22.
 */
var express = require('express');
var router = express.Router();
var Promise = require('promise');
var logger = require('log4js').getLogger('article');
var commonUtils = require('./../../utils/commonUtils');
var articleService = require('../service/ArticleService')
var newsService = require('../service/NewsService')
var memberService = require('../service/MemberService');
var attentionService = require('../service/AttentionService');
var resourcesService = require('../service/ResourcesService');
var worksService = require('../service/WorksService');
var qrcodeService = require('../service/QrcodeService');
var config = require('../../../config')
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var imageinfo = require('imageinfo');

//首页
router.post('/index',function(req,res,next){
    var type = req.body.type;
    var pageNo = req.body.pageNo;
    var memberId = req.body.memberId;
    if(!pageNo) {
        pageNo = 1;
    }
    var pageSize = 5;
    if(!type){
        type = 1;
    }
    //获取新闻
    var data = {};
    newsService.getNewsDel().then(function(news){
        //data.news = news;
        return Promise.resolve(data);
    }).then(function(){
        if(type==1){
            //获取最新文章
            return articleService.pageForTime(pageNo,pageSize).then(function(articles){
                data.articles = articles;
                return Promise.resolve(data);
            })
        }else if(type==2){

            //获取人气文章
            return articleService.pageForLike(pageNo,pageSize).then(function(articles){
                data.articles = articles;
                return Promise.resolve(data);
            })
        }else if(type==3){
            //获取达人
            return memberService.pageForFans(pageNo,pageSize).then(function(members){
                data.members = members;
                return Promise.resolve(data);
            })
        }

    }).then(function(){
       //获取关注状态
        if(memberId){
            if(type==3){
                var queue = [];
                data.members.forEach(function(item){
                    queue.push(
                        attentionService.checkAttention(memberId,item.id,1).then(function(attention){
                            if(attention&&attention.length>0){
                                item.attentionFlag=true;
                            }
                            else{
                                item.attentionFlag = false;
                            }
                        })
                    )
                })
                return Promise.all(queue);
            }else{
                var queue = [];
                data.articles.forEach(function(item){
                    queue.push(
                        attentionService.checkAttention(memberId,item.memberId,1).then(function(attention){

                            if(attention&&attention.length>0){
                                item.attentionFlag=true;
                            }
                            else{
                                item.attentionFlag = false;
                            }
                        })
                    )
                })
                return Promise.all(queue);
            }
        }else{
            if(type==3){
                data.members.forEach(function(item){
                    item.attentionFlag = false;
                })
            }else{
                data.articles.forEach(function(item){
                    item.attentionFlag = false;
                })
            }
        }
    }).then(function(){
        if(memberId&&type!=3){
            var queue = [];
            data.articles.forEach(function(item){
                item.likeFlag = false;
                queue.push(
                    articleService.checkLike(memberId,item.id).then(function(likes){
                            if(likes&&likes.length>0){
                                item.likeFlag = true;
                            }
                    })
                )
            })
            return Promise.all(queue);
        }
        if(!memberId&&type!=3){
            data.articles.forEach(function(item){
                item.likeFlag = false;
            })
        }
    }).then(function(){
        if(type!=3){
            data.articles.forEach(function (item) {
                if(item&&item.bak4){
                    var imageData = fs.readFileSync(config.main.fileUploadPath+item.bak4);
                    var info = imageinfo(imageData);
                    item.imageWidth = info.width;
                    item.imageHeight = info.height;
                }
            })
        }


    }).then(function(){
        res.json({"success":true,"data":data});
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({"success":false,"msg":"网络异常"});
    })

})

router.post('/info',function(req,res,next){
    var memberId = req.body.memberId;
    var articleId = req.body.articleId;
    if(!articleId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    //获取文章详情
    articleService.getById(articleId).then(function(article){
        if(article){
            return Promise.resolve(article);
        }else{
            return Promise.resolve(99);
        }
    }).then(function(article){
        if(article&&article!=99){
            if(memberId){
                return attentionService.checkAttention(memberId,article.memberId,1).then(function(atts){
                    if(atts&&atts.length>0){
                        article.attentionFlag = true;
                    }else{
                        article.attentionFlag = false;
                    }
                    return Promise.resolve(article);
                }).then(function (article) {
                    return articleService.checkCollect(memberId,article.id).then(function (cols) {
                        if(cols&&cols.length>0){
                            article.collectFlag = true;
                        }else{
                            article.collectFlag = false;
                        }
                        return Promise.resolve(article);
                    }).then(function (article) {
                        return articleService.checkLike(memberId,article.id).then(function (liks) {
                            if (liks && liks.length > 0) {
                                article.likeFlag = true;
                            } else {
                                article.likeFlag = false;
                            }
                            return Promise.resolve(article);
                        })
                    })
                })
            }else{
                article.attentionFlag = false;
                return Promise.resolve(article);
            }
        }else{
            return Promise.resolve(article);
        }
    }).then(function(article){
        if(article&&article!=99){
            return resourcesService.getByArticleId(article.id).then(function(rs){
                article.resources = rs;
                return Promise.resolve(article);
            })
        }else{
            return Promise.resolve(article);
        }
    }).then(function(article){
        if(article&&article!=99){
            res.json({'success':true,'article':article});
        }else if(article==99){
            res.json({'success':false,'msg':'该作品不存在',status:-1});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })


})
//发现
router.post('/find',function(req,res,next){
    var type = req.body.type;
    var orderBy = req.body.orderBy;
    if(!type){type=1};
    if(!orderBy){orderBy=1};
    var pageSize = 24;
    var pageNo = req.body.pageNo;
    if(!pageNo){pageNo=1};
    articleService.find(type,orderBy,pageNo,pageSize).then(function(articles){
        var data = {};
        data.articles = articles;
        res.json({'success':true,'data':data});
    },function(err){
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    });

})
router.post('/save',function(req,res,next){
    var form = new multiparty.Form();
    form.encoding = 'utf-8';
    form.uploadDir = config.main.fileUploadPath;
    form.parse(req, function(err, fields, files) {
        if(!fields){
            res.json({'success':false,'msg':'参数缺失'});
            return;
        }
        var title = fields.title[0];
        var memberId = fields.memberId[0];
        var type = fields.type[0];
        var content = fields.content[0];

        new Promise(function(fulfil,reject){
            if(err){
                reject(null);
            }else{
                fulfil(files);
            }
        }).then(function(files){
                if(!files){
                    return Promise.resolve(null);
                }else{
                    var queue = [];
                    files.upload.forEach(function(item,i){
                        queue.push(articleService.getFileName(item,i));
                    })
                    return Promise.all(queue);
                }
            }).then(function(fileNames){
                if(fileNames){
                        var imgUrl = fileNames[0];
                        var article = {};
                        article.memberId = memberId;
                        return memberService.getById(memberId).then(function(member){
                            if(member){
                                article.memberName = member.username;
                                article.memberImgUrl = member.headImgUrl;
                                article.title = title;
                                article.type = type;
                                article.content = content;
                                article.imgUrl = imgUrl;
                                article.commentNum = 0;
                                article.collectNum = 0;
                                article.likeNum = 0;
                                article.createTime = new Date();
                                article.fileNames = fileNames;
                                article.bak1 = 0;
                                if(files.mainUpload){
                                    return articleService.getFileName(files.mainUpload[0],0).then(function (fName) {
                                        article.bak4 = fName;
                                        return Promise.resolve(article);
                                    })
                                }else{
                                    return Promise.resolve(article);
                                }

                            }else{
                                return Promise.resolve(null);
                            }
                        })
                }else{
                    return Promise.resolve(null);
                }
            }).then(function(article){
                if(article){
                    return articleService.save(article).then(function(result){
                        if(result){
                            result.fileNames = article.fileNames;
                            return Promise.resolve(result);
                        }else{
                            return Promise.resolve(null);
                        }
                    })

                }else{
                    return Promise.resolve(null);
                }

            }).then(function(article){
                if(article){
                        var fileNames = article.fileNames;
                        var articleId = article.insertId;
                        var resource = [];
                        resource.articleId = articleId;
                        resource.memberId = memberId;
                        resource.createTime = new Date();
                        var queue = [];
                        fileNames.forEach(function(item){
                            resource.imgUrl = item;
                            queue.push(resourcesService.save(resource));
                        })
                        return Promise.all(queue);
                }else{
                    return Promise.resolve(null);
                }
            }).then(function(r){
                if(r){
                    res.json({'success':true});
                }else{
                    res.json({'success':false,'msg':'操作失败'});
                }

            },function(err){
                logger.error(err);
                res.json({'success':false,'msg':'网络异常'});
            })
    })
})



router.post('/saves',function(req,res,next){
    var params = req.body.params;
    var title = req.body.title;
    var memberId = req.body.memberId;
    var type = req.body.type;
    var imgUrl = req.body.imgUrl;
    var content = req.body.content;
    if(!memberId||!title||!params){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    memberService.getById(memberId).then(function(member){
        if(member){
            var memberName = member.username;
            var memberImgUrl = member.headImgUrl;
            var article = {};
            article.memberId = memberId;
            article.memberName = memberName;
            article.memberImgUrl = memberImgUrl;
            article.title = title;
            article.imgUrl=imgUrl;
            article.content = content;
            article.type = type;
            article.commentNum = 0;
            article.collectNum = 0;
            article.likeNum = 0;
            article.createTime = new Date();

            return Promise.resolve(article);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(article){
        if(article){
            return articleService.save(article).then(function(result){
                if(result){
                    return Promise.resolve(result);
                }else{
                    return Promise.resolve(null);
                }
            });
        }else{
            return Promise.resolve(null);
        }

    }).then(function(article){
        if(article){
            var articleId = article.insertId;
            var queue = [];
            for(k in params){
                var imgUrl = k;
                var content = params[k];
                var resource = {};
                resource.memberId = memberId;
                resource.articleId = articleId;
                resource.imgUrl = imgUrl;
                resource.bak5 = content;
                resource.createTime = new Date();
                queue.push(resourcesService.save(resource));
            }
            return Promise.all(queue);
        }else{
            return Promise.resolve(null);
        }

    }).then(function(result){
        if(result){
            res.json({'success':'true'});
        }else{
            res.json({'success':'false','msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
    })

})


router.post('/attention',function(req,res,next){
    var memberId = req.body.memberId;
    var attentionId = req.body.attentionId;
    if(!memberId||!attentionId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var attention = {};
    attention.articleId = attentionId;
    attention.memberId = memberId;
    attention.status = 0;
    attention.createTime = new Date();

    articleService.attention(attention).then(function(r){
        if(r){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);

    })



})

router.post('/like',function(req,res,next){
    var memberId = req.body.memberId;
    var likeId = req.body.likeId;
    if(!memberId||!likeId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var like = {};
    like.articleId = likeId;
    like.memberId = memberId;
    like.status = 0;

    articleService.like(like).then(function(r){
        if(r){
            return Promise.resolve(r);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return articleService.getById(likeId).then(function(ar){
                if(ar){
                    if(r==99){
                        ar.hasLike = true;
                    }
                    return Promise.resolve(ar);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(ar){
        if(ar){
            if(ar.hasLike){
                return Promise.resolve(ar);
            }else{
                var likeNum = ar.likeNum;
                likeNum++;
                ar.likeNum = likeNum;
                return articleService.plusLike(ar).then(function(r){
                    if(r){
                        return Promise.resolve(r);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){

            res.json({'success':true});
        }else{

            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'操作失败'});
    })



})

router.post('/unLike',function(req,res,next){
    var memberId = req.body.memberId;
    var likeId = req.body.likeId;
    if(!memberId||!likeId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var like = {};
    like.articleId = likeId;
    like.memberId = memberId;
    like.status = 0;

    articleService.unLike(like).then(function(r){
        if(r){
            return Promise.resolve(r);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return articleService.getById(likeId).then(function(ar){
                if(ar){
                    if(r==99){
                        ar.hasLike = true;
                    }
                    return Promise.resolve(ar);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(ar){
        if(ar){
            if(ar.hasLike){
                return Promise.resolve(ar);
            }else{
                var likeNum = ar.likeNum;
                likeNum--;
                ar.likeNum = likeNum;
                return articleService.plusLike(ar).then(function(r){
                    if(r){
                        return Promise.resolve(r);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){

            res.json({'success':true});
        }else{

            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'操作失败'});
    })



})

router.post('/collect',function(req,res,next){
    var memberId = req.body.memberId;
    var collectId = req.body.collectId;
    if(!memberId||!collectId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var collect = {};
    collect.articleId = collectId;
    collect.memberId = memberId;
    collect.status = 0;

    articleService.collect(collect).then(function(r){
        if(r){
            return Promise.resolve(r);

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return articleService.getById(collectId).then(function(ar){
                if(ar){
                    if(r==99){
                        ar.hasCollect = true;
                    }
                    return Promise.resolve(ar);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(ar){
        if(ar){
            if(ar.hasCollect){
                return Promise.resolve(ar);
            }else{
                var collectNum = ar.collectNum;
                collectNum++;
                ar.collectNum = collectNum;
                return articleService.plusCollect(ar).then(function(r){
                    if(r){
                        return Promise.resolve(r);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){

            res.json({'success':true});
        }else{

            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'操作失败'});
    })

})

router.post('/unCollect',function(req,res,next){
    var memberId = req.body.memberId;
    var collectId = req.body.collectId;
    if(!memberId||!collectId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var collect = {};
    collect.articleId = collectId;
    collect.memberId = memberId;
    collect.status = 0;

    articleService.unCollect(collect).then(function(r){
        if(r){
            return Promise.resolve(r);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return articleService.getById(collectId).then(function(ar){
                if(ar){
                    if(r==99){
                        ar.hasCollect = true;
                    }
                    return Promise.resolve(ar);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(ar){
        if(ar){
            if(ar.hasCollect){
                return Promise.resolve(ar);
            }else{
                var collectNum = ar.collectNum;
                collectNum--;
                ar.collectNum = collectNum;
                return articleService.plusCollect(ar).then(function(r){
                    if(r){
                        return Promise.resolve(r);
                    }else{
                        return Promise.resolve(null);
                    }
                })
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){

            res.json({'success':true});
        }else{

            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'操作失败'});
    })

})

router.post('/comment',function(req,res,next){
    var memberId = req.body.memberId;
    var articleId = req.body.articleId;
    var content = req.body.content;
    logger.debug('------------------------'+content+'-----------------------------')
    if(!memberId||!articleId||!content){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    var comment = {};
    comment.articleId = articleId;
    comment.memberId = memberId;
    comment.content = content;
    comment.bak1 = 0;
    comment.bak2 = 0;
    comment.createTime = new Date();
    var commentId = null;
    articleService.comment(comment).then(function(r){
        if(r){
            commentId = r.insertId;
            return Promise.resolve(r);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){
            return articleService.getById(articleId).then(function(ar){
                if(ar){
                    return Promise.resolve(ar);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(ar){
        if(ar){
            var commentNum = ar.commentNum;
            commentNum++;
            ar.commentNum = commentNum;
            return articleService.plusComment(ar).then(function(r){
                if(r){
                    return Promise.resolve(r);
                }else{
                    return Promise.resolve(null);
                }
            })
        }else{
            return Promise.resolve(null);
        }
    }).then(function(r){
        if(r){

            res.json({'success':true,'commentId':commentId});
        }else{

            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'操作失败'});
    })

})

//搜索
router.post('/search', function (req, res, next) {
    var content = req.body.content;
    var pageNo = req.body.pageNo;
    if(!pageNo) {
        pageNo = 1;
    }
    var pageSize = 8;
    var memberId = req.body.memberId;
    if(!content){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    articleService.search(content,pageNo,pageSize).then(function (ars) {

        return Promise.resolve(ars);

    }).then(function (ars) {
        if(memberId){
            var queue = [];
            ars.forEach(function(item){
                queue.push(
                    attentionService.checkAttention(memberId,item.memberId,1).then(function(attention){
                        if(attention&&attention.length>0){
                            item.attentionFlag=true;
                        }
                        else{
                            item.attentionFlag = false;
                        }
                        return Promise.resolve(item);
                    })
                )
            })
            return Promise.all(queue);
        }else{
            ars.forEach(function (item) {
                item.attentionFlag = false;
            })
            return Promise.resolve(ars);
        }
    }).then(function (ars) {
        if(memberId){
            var queue = [];
            ars.forEach(function(item){
                item.likeFlag = false;
                queue.push(articleService.checkLike(memberId,item.id).then(function (hasLike) {
                    if(hasLike&&hasLike.length>0){
                        item.likeFlag = true;
                    }
                    return Promise.resolve(item);
                }))
            })
            return Promise.all(queue);
        }else{
            ars.forEach(function (item) {
                item.attentionFlag = false;
            })
            return Promise.resolve(ars);
        }
    }).then(function (ars) {
        if(ars){
            ars.forEach(function (item) {
                if(item&&item.bak4){
                    var imageData = fs.readFileSync(config.main.fileUploadPath+item.bak4);
                    var info = imageinfo(imageData);
                    item.imageWidth = info.width;
                    item.imageHeight = info.height;
                }
            })
        }
        var data = {};
        data.articles = ars;
        res.json({'success':true,'data':data});
    }, function (err) {
        logger.error(err);
        console.log(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})


router.post('/delete', function (req, res, next) {

    var id = req.body.id;
    if(!id){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }

    articleService.delete(id).then(function (r) {
        if(r){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':"操作失败"});
        }
    }, function (err) {
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })
})


router.post('/likeMember', function (req, res, next) {
    var articleId = req.body.articleId;
    var pageNo = req.body.pageNo||1;
    var pageSize = 10;
    if(!articleId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    articleService.getLikes(articleId,pageNo,pageSize).then(function (members) {

        return Promise.resolve(members);
    }).then(function (members) {
        res.json({'success':true,'data':members});
    }, function (err) {
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })
    
})





//分享作品
router.get('/shareWorks',function(req,res,next){
    var id = req.query.id;
    var type = req.query.type;
    if(!id&&!type){
        res.state(404).end();
        return;
    }
    if(1==type){
        articleService.getById(id).then(function (article) {
            var data = {};
            data.article = article;
            return Promise.resolve(data);

        }).then(function (data) {
            var memberId = data.article.memberId;
            return resourcesService.getByArticleId(id).then(function (res) {
                data.res = res;
                return Promise.resolve(data);
            })
        }).then(function (data) {
            return qrcodeService.getQrcode().then(function (qrcode) {
                data.qrcode = qrcode;
                return Promise.resolve(data);
            })
        }).then(function (data) {
            return memberService.getById(data.article.memberId).then(function (mem) {
                data.member = mem;
                data.type = type;
                res.render('shoot/views/works',data);
            })
        })
    }else{
        worksService.getById(id).then(function (works) {
            var data = {};
            data.works = works;
            return Promise.resolve(data);

        }).then(function (data) {
            return qrcodeService.getQrcode().then(function (qrcode) {
                data.qrcode = qrcode;
                return Promise.resolve(data);
            })
        }).then(function (data) {
            var memberId = data.works.memberId;
            return memberService.getById(memberId).then(function (mem) {
                data.member = mem;
                data.type = type;
                res.render('shoot/views/works',data);
            })
        })
    }
})

module.exports = router;
